import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { SearchBar } from 'antd-mobile';
import styled from 'styled-components';
import * as userActions from 'actions/user';
import * as friendActions from 'actions/friend';
import UserItem from 'components/userItem';

const Wrapper = styled.ul`
    background-color: #fff;
    border-bottom: 1px solid #ddd;
`
@withRouter
@connect(state => ({
    userList: state.user.list,
    user: state.login.user
}), dispatch => ({
    userActions: bindActionCreators(userActions, dispatch),
    friendActions: bindActionCreators(friendActions, dispatch)
}))
export default class Friend extends Component {
    constructor(props) {
        super(props);
        this.state = {

        }
    }
    handleChange = value => {
        this.setState({
            value
        })
    }
    handleSubmit = () => {
        this.props.userActions.getUserList(this.state.value);
    }
    handleClear = () => {
        this.setState({
            value: ''
        })
    }
    handleClick = id => {
        const { friendActions, user } = this.props;
        friendActions.friendAdd({from: user.id, to: id}).then(res => {
            if (res) {
                this.props.history.push('/home');
            }
        })
    }
    render() {
        const { value } = this.state;
        const { userList } = this.props;
        return (
            <div>               
                <SearchBar 
                    placeholder='搜索联系人'
                    value={value}
                    onChange={this.handleChange}
                    onSubmit={this.handleSubmit}
                    onClear={this.handleClear}
                />
                <Wrapper>
                    {
                        userList.map(list => <UserItem {...list} key={list._id} onClick={() => { this.handleClick(list._id); }}/>)
                    }
                </Wrapper>
            </div>
        )
    }
}